package service

import (
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"sync"
	"tapay-ws/global"
	"tapay-ws/internal/model"
)

const (
	storeKeyPattern = "%d_%d"
)

type SendMsgRequest struct {
	UserId   uint32          `json:"user_id" form:"user_id" binding:"required,gte=1"`
	UserType uint8           `json:"user_type" form:"user_type" binding:"required,gte=1"`
	Body     string          `json:"body" form:"body" binding:"required,min=1"`
	Action   global.WsAction `json:"action" form:"action" binding:"required"`
}

// 用户结构体

type User struct {
	ID       uint32
	UserType uint8
	Conn     *websocket.Conn
}

var users sync.Map

func (svc *Service) AddUserConnList(userId uint32, userType uint8, conn *websocket.Conn) (*User, error) {
	// 创建用户
	user := &User{
		ID:       userId,
		UserType: userType,
		Conn:     conn,
	}
	// 将用户加入用户列表
	key := fmt.Sprintf(storeKeyPattern, user.ID, user.UserType)
	loadedConn, loaded := users.LoadOrStore(key, user)
	if loaded {
		if oldUser, ok := loadedConn.(*User); ok {
			err := svc.CloseConn(oldUser, "old")
			if err != nil {
				return nil, err
			}
		}
		users.Store(key, user)
	}
	//插入用户在线表
	err := svc.dao.CreateUserOnline(model.UserOnline{Uid: userId, UserType: userType})
	return user, err
}

func (svc *Service) CloseConn(user *User, msg string) error {
	log.Printf("=====================uid[%d],userType[%d] Close Conn ==================== msg:%s\n", user.ID, user.UserType, msg)
	// 连接关闭时从用户列表中移除用户信息
	users.Delete(user.ID)
	// 关闭连接
	user.Conn.Close()
	//更新用户在线表
	return svc.dao.UpdateUserOffline(user.ID, user.UserType)
}

func (svc *Service) GetConn(userId uint32, userType uint8) (conn *websocket.Conn) {
	key := fmt.Sprintf(storeKeyPattern, userId, userType)
	if value, ok := users.Load(key); ok {
		if user, ok := value.(*User); ok {
			conn = user.Conn
		}
	}
	return
}
